<template>
<el-upload
    class="avatar-uploader"
    :action="BASE_URL+'/upload/add'"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :headers="headers"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl" :src="IMG_URL+imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>
<script setup lang='ts'> 
 import { ElMessage, UploadProps } from 'element-plus';
import { Plus } from '@element-plus/icons-vue'
import {reactive,defineModel} from 'vue';


const imageUrl=defineModel();
 

 const BASE_URL=import.meta.env.VITE_BASE_URL;
 const IMG_URL=import.meta.env.VITE_IMG_URL;
 

 const headers=reactive({
  Authorization:sessionStorage.getItem('token')
})

 const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response
) => {
   console.log("上传成功",response);
   if(response.errCode==10000){
    imageUrl.value=response.data;
 
   }
   
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {

    const rawFiles=['image/jpeg','image/gif','image/jpg','image/png','image/bmp']
  if ( !rawFiles.includes(rawFile.type)) {
    ElMessage.error('请上传图片文件!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('上传的文件不能大于2MB!')
    return false
  }
  return true
}

</script>
<style scoped>
.avatar-uploader .avatar {
  width:80px;
  height: 80px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  text-align: center;
}
</style>